<template>
  <div class="conversation-friends">
    <el-row class="checkhuihua" type="flex" justify="center">
      <el-col :span="12">
        <el-button size="small" :type="checkhuihua==0 ? 'success' : 'plain'" @click="changeCheck(0)">聊天        <div
            v-if="weidu1>0"
            class="tip"
            :title="weidu1"
            v-text="weidu1 < 99 ? weidu1 : '...'"
          ></div></el-button>

      </el-col>
      <el-col :span="12">
        <el-button size="small" :type="checkhuihua==1 ? 'success' : 'plain'" @click="changeCheck(1)">群        <div
            v-if="weidu2>0"
            class="tip"
            :title="weidu2"
            v-text="weidu2 < 99 ? weidu2 : '...'"
          ></div></el-button>

      </el-col>
    </el-row>

    <!-- 搜索 -->
    <div class="search-box">
      <el-input
        v-model="searchInfo"
        prefix-icon="el-icon-search"
        type="text"
        placeholder="搜索"
        maxlength="20"
        size="small"
        show-word-limit
        @keyup.enter.native="searchChange"
      ></el-input>
    </div>

    <!-- 一键设为已读 | 仅展示未读  -->
    <el-row style="margin: 5px" type="flex" justify="center">
      <el-button size="small" @click="autoRead">一键设为已读</el-button>
      <el-button size="small" :type="onlyUnRead ? 'warning' : 'plain'" @click="findUnReadMsg">仅展示未读</el-button>
    </el-row>

    <!-- 会话列表 -->
    <div id="friends-list" class="friends-content scroll" @scroll="handlerScroll">
      <div
        v-for="(message, index) in searchInfo ? searchResult : conversations"
        :key="index"
        class="friend-info"
        :class="{
          selected: currentFriendId === message.UserName
        }"
        @click="$parent.choseFriend(message)"

      >
        <!-- 头像和提示 -->
        <div class="avatar-tip">
          <!-- 头像 -->
          <el-avatar :key="message.Avatar" shape="square" :size="34" :src="message.Avatar">
            <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
          </el-avatar>
          <!-- 未读消息数 -->
          <div
            v-if="
              !message.IsSilent &&
                message.UnreadCnt &&
                message.Digest &&
                !message.Digest.startsWith('你已添加了') &&
                !message.Digest.startsWith('以上是打招呼的内容')
            "
            class="tip"
            :title="message.UnreadCnt"
            v-text="message.UnreadCnt < 99 ? message.UnreadCnt : '...'"
          ></div>
        </div>
        <!-- 昵称和消息内容 -->
        <div class="nick-content">
          <!-- 昵称 -->
          <div class="friend-nick ellipsis" v-text="message.ShowName"></div>
          <!-- 消息内容 -->
          <div v-if="message.Digest" class="chat-content ellipsis" v-text="message.Digest.replace('%s:', '')"></div>
          <div v-else class="chat-content ellipsis" v-text="''"></div>
        </div>
        <!-- 时间 | 刷新 | 置顶 | 免打扰 -->
        <div class="time-disturb">
          <div v-text="$options.filters.timeFilter2(message.UpdateTime)"></div>
          <div class="opration-btns">
            <template v-if="message.UserName !== 'notifymessage'">
              <!-- 置顶 -->
              <i
                class="el-icon-upload2"
                :class="{ 'top-convs': message.IsTop }"
                aria-hidden="true"
                title="置顶"
                @click.stop="setTop(message)"
              ></i>
              <!-- 刷新 -->
              <i
                class="fa fa-retweet sigle-fresh"
                aria-hidden="true"
                @click.stop="$parent.getFriendDetail(message)"
              ></i>
              <!-- 免打扰 -->
              <i
                class="el-icon-close-notification"
                aria-hidden="true"
                :class="{
                  'msg-silent': message.IsSilent
                }"
                @click="msgSilent(message)"
              ></i>
            </template>
          </div>
        </div>
      </div>
      <div v-if="currentWeChatId" class="current-info-null">
        <el-button size="small" @click="queryMoreConv">加载更多</el-button>
        <el-button size="small" @click="queryMoreConv('all')">加载全部</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { TriggerConversationPushTask } from '@/api/webSocketApi'

// const notifyImg = require('assets/svg/conversation-notify-message.svg')

export default {
  data() {
    return {
      maxNumber: 20, // 默认显示20条数据
      searchInfo: '', // 搜索内容
      searchResult: [], // 搜索结果
      onlyUnRead: false, // 只展示未读
      conversUnread: [],
      checkhuihua:0,
      weidu1:0,
      weidu2:0
    }
  },
  computed: {
    ...mapGetters({
      currentConvs: 'conversation/currentConvs', // 会话列表
      currentFriendId: 'conversation/currentFriendId', // 当前页面回显
      currentWeChatId: 'conversation/currentWeChatId' // 当前选择的微信
    }),
    // 按条件重新排序会话列表
         conversations() {
          let fitler = this.checkhuihua == 0 ? false: true
           if (this.onlyUnRead) {
             const cl = this.currentConvs.filter((x) => {
            
               return (!!x.UnreadCnt && x.qun == fitler) || (this.conversUnread.indexOf(x.WeChatId + x.UserName) >= 0 && x.qun == fitler)
             })
             return cl
           } else {
             // 置顶的消息
             const tc = this.currentConvs.filter((x) => {
               return x.IsTop && x.qun == fitler
             })
             // 其他的消息
             const nc = this.currentConvs.filter((x) => {
               return !x.IsTop && x.qun == fitler
             })
             const cif = tc.concat(nc).slice(0, this.maxNumber)
             return cif 
           }
         }
    
  },
  watch: {
    searchInfo() {
      this.debounceInput()
    },
    // 切换微信 重置最大显示条数
    currentWeChatId() {
      this.maxNumber = 20
      this.onlyUnRead = false
      this.conversUnread = []
    }
  },
  created() {
    // 防抖
    this.debounceInput = this._.debounce(this.debounceInput, 500)
  },
  watch:{
    currentConvs(val){
      console.log(val)
    }
  },
  methods: {
    changeCheck(index){
      console.log(index)
      this.checkhuihua = index
    },
    // 一键设为已读
    autoRead() {
      this.currentConvs.forEach((x) => {
        if (x.UnreadCnt > 0) {
          this.$parent.setMessageRead(x)
        }
      })
    },
    // 快速定位未消息 默认定位到第一个未读消息
    findUnReadMsg() {
      this.onlyUnRead = !this.onlyUnRead
      if (this.onlyUnRead) {
        const unreadedConvs = []
        this.currentConvs.forEach((x) => {
          if (x.UnreadCnt) {
            unreadedConvs.push(x.WeChatId + x.UserName)
          }
        })
        this.conversUnread = unreadedConvs
      } else {
        this.conversUnread = []
      }
      // let findIndex = -1
      // for (let index = 0; index < this.currentConvs.length; index++) {
      //   const element = this.currentConvs[index]
      //   if (!element.IsSilent && element.UnreadCnt > 0) {
      //     findIndex = index
      //     break
      //   }
      // }
      // if (findIndex >= this.maxNumber) {
      //   this.maxNumber = 20 + 5 * Math.ceil((findIndex + 1 - this.maxNumber) / 5)
      // }
      // setTimeout(() => {
      //   // 修改scroll
      //   const showDiv = document.getElementById('friends-list')
      //   if (findIndex !== -1 && showDiv.scrollHeight > showDiv.clientHeight) {
      //     showDiv.scrollTop = findIndex * 59
      //   }
      // }, ~~(findIndex / 20) * 100)
    },
    // 滚动加载
    handlerScroll() {
      const st = document.getElementById('friends-list').scrollTop
      const ch = document.getElementById('friends-list').clientHeight
      const sh = document.getElementById('friends-list').scrollHeight
      if (st + ch + 2 >= sh) {
        if (this.maxNumber <= this.currentConvs.length) {
          this.maxNumber = this.maxNumber + 5
        }
      }
    },
    // 搜索框防抖
    debounceInput() {
      if (this.searchInfo) {
        const result = this.currentConvs.filter((x) => {
          return x.ShowName && x.ShowName.indexOf(this.searchInfo) >= 0
        })
        this.searchResult = result
      } else {
        this.searchResult = []
      }
    },
    // 消息免打扰
    msgSilent(message) {
      const content = {
        WeChatId: message.WeChatId, // 商家所属微信号
        ChatRoomId: message.UserName, // 群聊id
        Action: 6, // 指令
        IntValue: message.IsSilent ? 1 : 0 // IntValue=0 开启免打扰，IntValue=1 关闭免打扰
      }
      this.$store.dispatch('websocket/ChatRoomActionTask', content)
      this.$message.success('任务已经下发！')
    },
    // 消息置顶/取消置顶
    setTop(message) {
      const content = {
        WeChatId: message.WeChatId, // 商家所属微信号
        ChatRoomId: message.UserName, // 群聊id
        Action: 16, // 指令
        IntValue: message.IsTop ? 0 : 1 // IntValue=0 取消置顶，IntValue=1 置顶
      }
      this.$store.dispatch('websocket/ChatRoomActionTask', content)
      this.$message.success('任务已经下发！')
    },
    // 获取更多会话
    queryMoreConv(flag) {
      const ccl = this.currentConvs.length
      if (flag === 'all' || ccl === 0) {
        TriggerConversationPushTask(this.currentWeChatId, 0)
        return
      }
      if (ccl > 0) {
        const et = this.currentConvs[ccl - 1].UpdateTime
        const st = et - 3 * 24 * 60 * 60 * 1000
        TriggerConversationPushTask(this.currentWeChatId, st, et)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.conversation-friends {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #f7f7f7;
  border-right: solid #c3c3c3 1px;
  padding: 5px;

  .search-box {
    padding: 5px 0 5px;
  }

  .friends-content {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    overflow-x: hidden;

    .friend-info {
      height: 59px;
      min-height: 59px;
      // width: 210px;
      overflow: hidden;
      display: flex;
      cursor: pointer;

      .avatar-tip {
        height: 59px;
        width: 59px;
        position: relative;
        display: flex;
        align-items: center;
        padding-left: 5px;
        .tip {
          width: 20px;
          height: 20px;
          position: absolute;
          top: 0px;
          right: 0px;
          background: red;
          border-radius: 10px;
          color: white;
          text-align: center;
        }
      }

      .nick-content {
        width: 120px;
        min-width: 120px;
        padding-left: 9px;
        display: flex;
        flex-direction: column;
        align-self: center;

        .friend-nick,
        .chat-content {
          height: 20px;
          line-height: 20px;
        }
        .friend-nick {
          color: #333333;
          font-size: 14px;
        }
        .chat-content {
          color: #999999;
          font-size: 12px;
        }
      }

      .time-disturb {
        width: 70px;
        min-width: 70px;
        color: #999999;
        display: flex;
        align-items: center;
        justify-content: space-around;
        flex-direction: column;
        .sigle-fresh:hover {
          color: #41c0fc;
        }
        .opration-btns {
          display: flex;
          justify-content: space-between;
          width: 50px;

          .top-convs {
            color: #ff9f00;
          }
          .msg-silent {
            color: #ff9f00;
          }
        }
      }

      &:hover {
        background-color: #dedcdb;
      }
    }
    .current-info-null {
      text-align: center;
      margin-top: 10px;
    }
    .selected {
      background-color: #c8c6c6;
      &:hover {
        background-color: #c8c6c6;
      }
    }
  }
}
.checked{
  background-color: #dedcdb;
}
.checkhuihua{
  button{
    width: 100%;
    position: relative;
    .tip {
          width: 15px;
          height: 15px;
          position: absolute;
          top: 0px;
          right: 0px;
          background: red;
          border-radius: 10px;
          color: white;
          text-align: center;
        }
  }
}
</style>
